<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="活动赛事标题" prop="eventTitle" label-width="100px">
        <el-input
          v-model="queryParams.eventTitle"
          placeholder="请输入活动赛事标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="咨询电话" prop="eventPhone">
        <el-input
          v-model="queryParams.eventPhone"
          placeholder="请输入咨询电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="赛事报名结束时间"
        prop="enrollEndTime"
        label-width="130px"
      >
        <el-date-picker
          clearable
          v-model="queryParams.enrollEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择赛事报名结束时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:event:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:event:edit']"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:event:remove']"
          >删除
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport(queryParams)"
          v-hasPermi="['business:event:export']">导出
        </el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="eventList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动赛事标题" align="center" prop="eventTitle" />
      <el-table-column label="活动价格" align="center" prop="price" />
      <el-table-column label="活动赛事封面图" align="center" prop="eventImg">
        <template v-slot:default="scope">
          <el-image
            :src="scope.row.eventImg"
            :zoom-rate="2.4"
            :max-scale="8"
            :min-scale="0.9"
            :preview-src-list="[scope.row.eventImg]"
          />
        </template>
      </el-table-column>
      <el-table-column label="咨询电话" align="center" prop="eventPhone" />
      <el-table-column
        label="赛事报名开始时间"
        align="center"
        prop="enrollStartTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.enrollStartTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="赛事报名结束时间"
        align="center"
        prop="enrollEndTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.enrollEndTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="赛事开始时间"
        align="center"
        prop="startTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.startTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="赛事结束时间"
        align="center"
        prop="endTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.endTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template v-slot:default="scope">
          <span v-if="scope.row.state === 1">
            <el-tag type="info">待报名</el-tag>
          </span>
          <span v-if="scope.row.state === 2">
            <el-tag type="success">报名中</el-tag>
          </span>
          <span v-if="scope.row.state === 3">
            <el-tag type="danger">待开始</el-tag>
          </span>
          <span v-if="scope.row.state === 4">
            <el-tag type="success">进行中</el-tag>
          </span>
          <span v-if="scope.row.state === 5">
            <el-tag type="info">已结束</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:event:edit']"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleSignUpRecord(scope.row)"
            v-hasPermi="['business:event:enroll']"
            >报名记录
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:event:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      class="modal-wrap"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item
          label="活动赛事标题"
          prop="eventTitle"
          label-width="140px"
        >
          <el-input
            v-model="form.eventTitle"
            placeholder="请输入活动标题"
          />
        </el-form-item>
        <el-form-item label="活动价格" prop="price" label-width="140px">
          <el-input
            v-model="form.price"
            placeholder="请输入活动价格"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item
          label="活动赛事封面图"
          prop="eventImg"
          label-width="140px"
        >
          <el-upload
            class="avatar-uploader"
            action
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleUploadForm"
            :accept="'.jpg,.png,.jpeg'"
          >
            <img v-if="imageUrl" :src="imageUrl" class="banner-img" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="咨询电话" prop="eventPhone" label-width="140px">
          <el-input v-model="form.eventPhone" placeholder="请输入咨询电话" />
        </el-form-item>
        <el-form-item
          label="赛事报名开始时间"
          prop="enrollStartTime"
          label-width="140px"
        >
          <el-date-picker
            clearable
            v-model="form.enrollStartTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择赛事报名开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="赛事报名结束时间"
          prop="enrollEndTime"
          label-width="140px"
        >
          <el-date-picker
            clearable
            v-model="form.enrollEndTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择赛事报名结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="赛事开始时间" prop="startTime" label-width="140px">
          <el-date-picker
            clearable
            v-model="form.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择赛事开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="赛事结束时间" prop="endTime" label-width="140px">
          <el-date-picker
            clearable
            v-model="form.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择赛事结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="赛事介绍" prop="eventDescribe" label-width="140px">
          <Wangeditor
            @changeData="handleEditorChange"
            :content="editorContent"
          />
          <div class="editBox">
            <div></div>
            <span>最高2000字</span>
          </div>
          
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="signUpVisible"
      width="50%"
      :before-close="handleSignUpClose"
    >
      <span slot="title" class="dialog-footer">
        报名记录
        <el-button type="primary" style="margin-left: 10px" @click="handleExport({status:1,eventEventsId:signUpRecordParams.eventEventsId})"
          >导出</el-button
        >
      </span>
      <el-table :data="signUpRecordData" style="width: 100%">
        <el-table-column prop="fullName" label="姓名"> </el-table-column>
        <el-table-column prop="age" label="年龄"> </el-table-column>
        <el-table-column prop="eventPhone" label="电话"> </el-table-column>
        <el-table-column prop="idcard" label="身份证号"> </el-table-column>
      </el-table>
      <pagination
        v-show="signUpRecordTotal > 0"
        :total="signUpRecordTotal"
        :page.sync="signUpRecordParams.pageNum"
        :limit.sync="signUpRecordParams.pageSize"
        @pagination="handleGetSignUpList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  addEvent,
  delEvent,
  getEvent,
  listEvent,
  updateEvent,
  activitySignUpRecord,
} from "@/api/business/event";
import { uploadImage } from "@/api/business/banner";
import Wangeditor from "@/components/WangEditor";
import { status } from "nprogress";
import dayjs from 'dayjs';

export default {
  name: "Event",
  components: { Wangeditor },
  data() {
    const validateSignUpEndTime = (rule, value, callback) => {
      if (
        value &&
        new Date(value).getTime() <
          new Date(this.form.enrollStartTime).getTime()
      ) {
        callback(new Error("赛事报名结束时间不能小于赛事报名开始时间"));
      } else {
        callback();
      }
    };

    const validateEndTime = (rule, value, callback) => {
      if (
        value &&
        new Date(value).getTime() < new Date(this.form.startTime).getTime()
      ) {
        callback(new Error("赛事结束时间不能小于赛事开始时间"));
      } else {
        callback();
      }
    };

    const validateStartTime = (rule, value, callback) => {
      if (
        value &&
        new Date(value).getTime() < new Date(this.form.enrollEndTime).getTime()
      ) {
        callback(new Error("赛事开始时间不能小于赛事报名结束时间"));
      } else {
        callback();
      }
    };

    const validatePhone = (rule, value, callback) => {
      const telRegex = /^1[3456789]\d{9}$/;
      if (value && !telRegex.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 活动管理表格数据
      eventList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        eventType: 1,
        eventTitle: null,
        price: null,
        eventImg: null,
        eventPhone: null,
        enrollStartTime: null,
        enrollEndTime: null,
        startTime: null,
        endTime: null,
        eventDescribe: null,
        state: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        eventTitle: [
          { required: true, message: "活动赛事标题不能为空", trigger: "blur" },
        ],
        price: [
          { required: true, message: "活动价格不能为空", trigger: "blur" },
        ],
        eventImg: [
          {
            required: true,
            message: "活动赛事封面图不能为空",
            trigger: "blur",
          },
        ],
        eventPhone: [
          { required: true, message: "咨询电话不能为空", trigger: "blur" },
          {
            validator: validatePhone,
            message: "请输入正确的号码格式",
            trigger: "change",
          },
        ],
        enrollStartTime: [
          {
            required: true,
            message: "赛事报名开始时间不能为空",
            trigger: "blur",
          },
        ],
        enrollEndTime: [
          {
            required: true,
            message: "赛事报名结束时间不能为空",
            trigger: "blur",
          },
          {
            validator: validateSignUpEndTime,
            message: "赛事报名结束时间不能小于赛事报名开始时间",
            trigger: "blur",
          },
        ],
        startTime: [
          { required: true, message: "赛事开始时间不能为空", trigger: "blur" },
          {
            validator: validateStartTime,
            message: "赛事开始时间不能小于赛事报名结束时间",
            trigger: "blur",
          },
        ],
        endTime: [
          { required: true, message: "赛事结束时间不能为空", trigger: "blur" },
          {
            validator: validateEndTime,
            message: "赛事结束时间不能小于赛事开始时间",
            trigger: "blur",
          },
        ],
        eventDescribe: [
          { required: true, message: "赛事介绍不能为空", trigger: "blur" },
        ],
      },
      imageUrl: "",
      editorContent: "",
      signUpRecordParams: {
        pageNum: 1,
        pageSize: 10,
        status:1,
      },
      signUpVisible: false,
      signUpRecordData: [],
      signUpRecordTotal: 0,
      editorTextLen: 0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleSignUpClose() {
      this.signUpVisible = false;
    },
    // 活动报名记录
    handleSignUpRecord(data) {
      this.signUpVisible = true;
      this.signUpRecordParams.eventEventsId = data.id;
      this.handleGetSignUpList();
    },
    handleGetSignUpList() {
      activitySignUpRecord(this.signUpRecordParams).then((res) => {
        this.signUpRecordData = res.rows;
        this.signUpRecordTotal = res.total;
      });
    },
    // 上传图片
    async handleUploadForm(param) {
      const formData = new FormData();
      let loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      formData.append("file", param.file);
      try {
        const res = await uploadImage(formData, Math.floor(Math.random() * 10));
        this.imageUrl = res.data.url;
        this.form.eventImg = res.data.url;
        loading.close();
      } catch (e) {
        loading.close();
      }
    },
    handleEditorChange(html, text) {
      this.form.eventDescribe = html;
      this.editorTextLen = text.length;
      if (this.editorTextLen > 2000) {
        this.$message.error("赛事介绍最多2000字");
      }
    },
    /** 查询活动管理列表 */
    getList() {
      this.loading = true;
      listEvent(this.queryParams).then((response) => {
        this.eventList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        eventType: 1,
        eventTitle: null,
        eventImg: null,
        eventPhone: null,
        enrollStartTime: null,
        enrollEndTime: null,
        startTime: null,
        endTime: null,
        eventDescribe: null,
        state: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.imageUrl = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加活动赛事";
      this.editorContent = "";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getEvent(id).then((response) => {
        this.form = response.data;
        this.imageUrl = response.data.eventImg;
        this.editorContent = response.data.eventDescribe;
        this.open = true;
        this.title = "修改活动赛事";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.editorTextLen > 2000) {
            this.$message.error("赛事介绍最多2000字");
            return;
          }
          if (this.form.id != null) {
            updateEvent(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEvent(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除活动赛事？")
        .then(function () {
          return delEvent(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport(params) {
      const time = dayjs().format('YYYY-MM-DD HH:mm:ss');
      this.download(
        "business/record/export",
        {
          ...params
        },
        `${this.signUpRecordData[0].eventTitle}_报名记录_${time}.xlsx`
      );
    },
    // 上传图片
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 20;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 20MB!");
      }
      return isLt2M;
    },
  },
};
</script>

<style scoped lang="scss">
.modal-wrap {
  ::v-deep .el-dialog__body {
    height: 600px;
    overflow-y: scroll;
  }
}

.avatar-uploader {
  ::v-deep .el-upload {
    width: 100px;
    height: 100px;
    border: 1px dotted #eee;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .avatar-uploader-icon {
    font-size: 24px;
  }
}

.banner-img {
  width: 100px;
  height: 100px;
  // margin-left: 20px;
}
.editBox{
  display: flex;
  justify-content: space-between;
}
</style>
